package org.kur.modularization.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import javafx.animation.TranslateTransition;
import javafx.application.Platform;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.concurrent.Worker;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Window;
import javafx.util.Duration;

public class MavenController {

    @FXML
    private TextField artifactId;

    @FXML
    private TextField groupId;

    @FXML
    private TextField jarPath;
    private File jarFile;

    @FXML
    VBox mavenRootPane;

    @FXML
    private TextField version;

    @FXML
    void chooseFile() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("请选择非模块化的Jar包");
        fileChooser.setInitialDirectory(new File(System.getProperty("user.dir")));
        FileChooser.ExtensionFilter jar = new FileChooser.ExtensionFilter("非模块化jar包", "*.jar");
        fileChooser.getExtensionFilters().add(jar);
        Window window = jarPath.getParent().getScene().getWindow();
        File file = fileChooser.showOpenDialog(window);
        if (file != null) {
            jarFile = file;
            jarPath.setText(file.getAbsolutePath());
        }
    }

    @FXML
    void closeMavenPane() {
        TranslateTransition transition = new TranslateTransition(Duration.seconds(0.6), mavenRootPane);
        transition.setFromY(340);
        transition.setToY(700);
        transition.play();
    }

    @FXML
    void mavenInstall() {
        String command = "mvn install:install-file -Dfile=" + jarFile.getAbsolutePath() + " -DgroupId=" + groupId.getText() + " -DartifactId=" + artifactId.getText() + " -Dversion=" + version.getText() + " -Dpackaging=jar";
        System.out.println(command);
        TextArea textArea = new TextArea();
        textArea.appendText(command + "\n");
        Service<String> service = new Service<>() {
            @Override
            protected Task<String> createTask() {
                return new Task<>() {
                    @Override
                    protected String call() {
                        try {
                            // 创建ProcessBuilder对象
                            ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", command);
                            builder.redirectErrorStream(true); // 将标准错误流和标准输出流合并为一个流
                            builder.directory(new File(System.getProperty("user.home")));
                            // 执行命令并获取结果
                            Process process = builder.start();
                            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")));
                            String line;
                            while ((line = reader.readLine()) != null) {
                                String finalLine = line;
                                Platform.runLater(() -> textArea.appendText(finalLine + "\n"));
                            }
                            reader.close();
                            process.destroy();
                        } catch (IOException e) {
                            Platform.runLater(() -> textArea.appendText(e.getMessage() + "\n"));
                        }
                        return "true";
                    }
                };
            }
        };


        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setGraphic(textArea);
        alert.initOwner(jarPath.getParent().getScene().getWindow());
        alert.setWidth(400);
        alert.setHeight(400);


        alert.show();
        if (!service.getState().equals(Worker.State.RUNNING)) {
            service.reset();
            service.start();
        } else {
            textArea.appendText("任务正在运行中\n");
        }

        service.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue.equals("true")) {
                textArea.appendText("<dependency>\n");
                textArea.appendText("  <groupId>" + groupId.getText() + "</groupId>\n");
                textArea.appendText("  <artifactId>" + artifactId.getText() + "</artifactId>\n");
                textArea.appendText("  <version>" + version.getText() + "</version>\n");
                textArea.appendText("</dependency>\n");
            }
        });


    }

    @FXML
    void initialize() {


    }

}
